<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link src="./node_modules/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="./fontawesome/css/all.min.css" />
    <script src="./fontawesome/js/all.min.js"></script>
    <link rel="stylesheet" href="./css/main.css" />
  </head>
  <body>
    <h1>登录</h1>

    <form name="form">
      <p>
        用户
        <input type="text" name="name" />
      </p>
      <p>
        密码
        <input type="password" name="password" />
      </p>
      <p>
        <button type="button" name="loginBtn">登录</button>
      </p>
    </form>
    <script type="module">
      import request from "./request.js";
      const form = document.form;

      if (localStorage.token) {
        //如果存在表示已经登录
        location.href = "./index.html";
        throw "";
      }

      form.loginBtn.onclick = async function () {
        const data = {
          name: form.name.value,
          password: form.password.value,
        };

        try {
          const res = await request.post("/login", data);
          localStorage.token = res.data;
          location.href = "./index.html";
        } catch (err) {
          console.log(err);
        }
      };
    </script>
  </body>
</html>
